package stuttgart.uni.pedometer;

import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.util.Log;

//where the work is done
public class PedometerService extends Service{
	
	final RemoteCallbackList<IRemoteServiceCallback> mCallbacks= new RemoteCallbackList<IRemoteServiceCallback>();
	
	private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
        public void registerCallback(IRemoteServiceCallback cb) {
            if (cb != null){
            	mCallbacks.register(cb);
            }
        }
        public void unregisterCallback(IRemoteServiceCallback cb) {
            if (cb != null){
            	mCallbacks.unregister(cb);
            }
        }
    };
    
    private Notification notification;
    private Pedometer pedometer;

    @Override
	public void onCreate() {
    	
    	//notification for start Foreground
    	notification = new Notification.Builder(this)
		.setOngoing(true)
		.setContentTitle("Pedometer")
		.setContentText("Measuring Steps")
		.setSmallIcon(R.drawable.notification_icon)
		.build();
    	
    	/*
    	 * For old Devices, API Level 11
    	 * 
    	notification = new Notification.Builder(this)
		.setOngoing(true)
		.setContentTitle("Pedometer")
		.setContentText("Measuring Steps")
		.setSmallIcon(R.drawable.notification_icon)
		.getNotification();
		*/
    	
    	//make it less likely that our service will be shut down
    	startForeground(1, notification);
    	
    	new Thread(){
    		public void run(){
    			//Start the Pedometer
    			pedometer = new Pedometer(PedometerService.this);
    		}
    	}.start();
  	
	}
    
    //function that calls Activitys updateUI function
    public void updateUI(PedometerData pedometerData){
    	final int N = mCallbacks.beginBroadcast();
        for (int i=0; i<N; i++) {
            try {
                mCallbacks.getBroadcastItem(i).updateUI(pedometerData);
            } catch (RemoteException e) {
                Log.d("PedometerService","RemoteException in updateUI");
            }
        }
        mCallbacks.finishBroadcast();
    }

	@Override
	public void onDestroy(){
		stopForeground(true);
		
		if(mCallbacks!=null){
			mCallbacks.kill();
		}
		if(pedometer!=null){
			pedometer.close();
		}
	}

	@Override
    public IBinder onBind(Intent intent) {
		Log.d("PedometerService"," on bind");
		return mBinder;
    }
	
	

	

	

}
